﻿using VI.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Linq;
using Volo.Abp.ObjectMapping;

namespace Demo.Abp.Extension;

/// <summary>
/// ABP应用服务扩展
/// </summary>
public static class ApplicationServiceExtensions
{
    /// <summary>
    /// 获取排序并分页的数据并转换成DTO
    /// </summary>
    /// <param name="service">应用服务</param>
    /// <param name="query">查询</param>
    /// <param name="input">分页条件</param>
    /// <typeparam name="TEntity">实体类数据类型</typeparam>
    /// <typeparam name="TDto">DTO数据类型</typeparam>
    /// <returns></returns>
    public static async Task<PagedResultDto<TDto>> ApplySortPagedResult<TEntity, TDto>(
        this ApplicationService service, IQueryable<TEntity> query, IPagedAndSortedResultRequest input)
        where TEntity : IEntity
        where TDto : IEntityDto
    {
        //获取异步执行器
        IAsyncQueryableExecuter AsyncExecuter =
            service.LazyServiceProvider.LazyGetRequiredService<IAsyncQueryableExecuter>();
        //获取对象映射器
        var ObjectMapper = service.LazyServiceProvider.LazyGetRequiredService<IObjectMapper>();
        //计算总数
        var totalCount = await AsyncExecuter.CountAsync(query);
        //排序
        query = query.ApplySorting(input);
        //分页
        query = query.ApplyPaging(input);
        //查询
        var entities = await AsyncExecuter.ToListAsync(query);
        //转换成结果
        var entityDtos = ObjectMapper.Map<List<TEntity>, List<TDto>>(entities);
        return new PagedResultDto<TDto>(
            totalCount,
            entityDtos
        );
    }
}